
import json

from django.http import HttpResponse

from entity.common.response import ResponseStatus, ResponseData
from userApp.login import userService
from userApp.service.email import emailService
from utils.transfer import transferToJson

def userRegister(request):
    response = None
    if request.method == 'POST':
        requestBody = json.loads(request.body)
        user = requestBody['user']
        code = user['emailCode']
        success = emailService.verfiyCode(user['email'],code)
        # from redis cache to verify is code exists
        if not success:
            response=ResponseData(False, ResponseStatus.OPERATION_FAIL, "验证码错误", [])
            return HttpResponse(transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)
        user = userService.saveUser(user)
        if user:
            request.session['user'] = transferToJson(user)
            response = ResponseData(True, ResponseStatus.SUCESS, "注册成功", [])
    if not response:
        response = ResponseData(False, ResponseStatus.OPERATION_FAIL, "用户名称重复", [])
    return HttpResponse(transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)

def sendEmailCode(request):
    response = None
    email = json.loads(request.body)['email']
    print(email)
    if  not email:
        response = ResponseData(False,ResponseStatus.PARAMETER_ERROR,"请输入邮箱",[])
    else:
        try:
            emailService.sendEmail(email)
            response = ResponseData(True,ResponseStatus.SUCESS,"验证码已经发送",[])
        except Exception as err:
            print(err)
            response = ResponseData(False,ResponseStatus.RESPONSE_FAIL,"发生错误,请稍后重试",[])
    return HttpResponse(transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)